package com.company.restaurant.dto.util;

import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import com.company.restaurant.dto.MessageIds;
import com.company.restaurant.dto.MessageWrapper;
import com.company.restaurant.dto.Protocol;

/**
 * Description of class. Created 5/16/14 1:24 PM
 * 
 * @author andrey.rodin@playtech.com
 */

public final class Packager {

    public static byte[] toByteArray(int codeId, int protocolId, Serializable message) {
        Protocol protocol = Protocol.getById(protocolId);
        MessageIds code = MessageIds.getByCode(codeId);
        byte[] result = null;
        switch (protocol) {
            case BINARY_JSON_SERIALIZABLE:
                String msg = (String) message;
                result = buildBinary(protocol, code, msg);
            default: {

            }
        }

        return result;
    }

    public static MessageWrapper unpackFromByteArray(int messageId, int protocolId, byte[] source) {
        Protocol protocol = Protocol.getById(protocolId);
        MessageWrapper<Serializable> messageWrapper = null;
        switch (protocol) {
            case BINARY_JSON_SERIALIZABLE:
                String msg = new String(source, Charset.forName("UTF-8"));
                messageWrapper = new MessageWrapper<Serializable>(messageId, protocolId, msg);
            default: {

            }
        }
        return messageWrapper;
    }

    private static byte[] buildBinary(Protocol protocol, MessageIds messageIds, String message) {
        byte[] bodyMsg = message.getBytes(Charset.forName("UTF-8"));
        ByteBuffer header = ByteBuffer.allocate(/* MessageID */4 + /* Protocol */4 + /* length */4);
        header.putInt(messageIds.getCode());
        header.putInt(protocol.getId());
        header.putInt(bodyMsg.length);

        ByteBuffer fullMsg = ByteBuffer.allocate(header.array().length + bodyMsg.length);
        fullMsg.put(header.array());
        fullMsg.put(bodyMsg);
        return fullMsg.array();
    }

}
